﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using DevExpress.XtraEditors.Repository;
using DevTeam;

using Kaliko.ImageLibrary;
using Kaliko.ImageLibrary.Filters;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Kalite
{
    public partial class Kontrol : XForm
    {
        public Kontrol()
        {
            InitializeComponent();
        }

        void Kontrol_FormClosing(object sender, FormClosingEventArgs e)
        {
            camControl1.StopLive();
            camControl1.ExitControl();
        }

        private void Kontrol_Load(object sender, EventArgs e)
        {
            this.Text = "Kalite Güvence";

            string username = "oaykut", password = "Lic059-59469";
            
            camControl1 = new sceye_menucam2.CamControl();
            //camControl1.PerformReset();
            camControl1.InitCameraExt(username, password);

            camControl1.StartLive();            //start live picture  
            camControl1.SetAnimation(1, 1);     //disable
            camControl1.SetColorMode(1);        //color mode
            camControl1.SetBrightness(65536);   //auto-brightness
            camControl1.SetAutoDetection(0);    //autodetection on
            camControl1.SetContrast(20);        //contrast 30 (0-100)
            camControl1.LaserSwitch(1);         //laser on
            camControl1.LEDSwitch(0);           //led light on

            bbiResimCek.ItemClick += bbiResimCek_ItemClick;
            bbiLanscape.ItemClick += bbiLanscape_ItemClick;
            //camControl1.MouseUp += new MouseEventHandler(camControl1_MouseUp);
            //camControl1.MouseDown += new MouseEventHandler(camControl1_MouseDown);
            //camControl1.NotifyImageReadyOnMemory += new sceye_menucam2.CamControl.NotifyImageReadyOnMemoryEventHandler(camControl1_NotifyImageReadyOnMemory);
            //camControl1.NotifyImageReady += new sceye_menucam2.CamControl.NotifyImageReadyEventHandler(camControl1_NotifyImageReady);

            this.FormClosing += new FormClosingEventHandler(Kontrol_FormClosing);

            gridView1.Init("GetKaliteKontrol", string.Empty); //GetAksesuarFull

            gridView1.OptionsBehavior.Editable = false;
            gridView1.Columns["DosyaNo"].OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            gridView1.FormatAsDate("DosyaTeslimTarihi");
            gridView1.SetViewCaption("Dosyalar");
            gridView1.AddSummary();

            RepositoryItemHyperLinkEdit riPOId = new RepositoryItemHyperLinkEdit();
            riPOId.SingleClick = true;
            gridView1.Columns["Sayfa"].ColumnEdit = riPOId;
            gridView1.RowCellClick += gridView1_RowCellClick;


            gridView1.BestFitColumns();
        }

        void bbiLanscape_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TakePhoto(true);
        }

        void bbiResimCek_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TakePhoto();
        }

        void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Sayfa")
                if (gridView1.GetFocusedDataRow()["Sayfa"].ToStr() != string.Empty)
                {
                    string DosyaNo = gridView1.GetFocusedDataRow()["DosyaNo"].ToStr();
                    using (Detay detay = new Detay(DosyaNo))
                        detay.ShowDialog();
                }
        }




        /*
        Point f = new Point();
        void camControl1_MouseDown(object sender, MouseEventArgs e)
        {
            f.X = e.X;
            f.Y = e.Y;
        }

        void camControl1_MouseUp(object sender, MouseEventArgs e)
        {
            camControl1.SetSelection(
                (short)f.X, (short)e.X,
                (short)f.Y, (short)e.Y);
        }

        ~Kontrol()
        {
        }
        */


        public byte[] ConvertImageToByteArray(Image imageToConvert)
        {
            byte[] Ret;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, ImageFormat.Jpeg);
                    Ret = ms.ToArray();
                }
            }
            catch (Exception) { return null; }
            return Ret;
        }

        void TakePhoto(bool Landscape = false)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                bbiResimCek.Enabled = bbiLanscape.Enabled = false;

                camControl1.SetSaveColorMode(1);
                camControl1.SetSaveDPI(400);
                camControl1.SetSaveAddParam(9);
                camControl1.GetLastFrameExt("test.jpg", 1);     //(0 = asynchronously, 1 = synchronously)
                //https://www.lires.de/dev_board/viewtopic.php?t=381&p=975
                //http://www.sceye.eu/en/sceye-lounge-sdk/147-sdk-forum/ocx-interface/snapshot-functions
                //http://www.sceye.eu/en/sceye-lounge-sdk/149-sdk-forum/ocx-interface/events

                //byte[] bytes =  File.ReadAllBytes("test.jpg");
                //i0 = i2 = Image.FromFile("test.png");
                //i2.Save(@"C:\Shared\" +  intParse(bsAksesuar, "AksesuarId").ToString() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss")+ ".png");

                using (Image i2 = Image.FromFile("test.jpg"))
                {
                    if (i2 != null)
                    {
                        if (Landscape)
                            i2.RotateFlip(RotateFlipType.Rotate90FlipNone);

                        string DosyaNo = gridView1.GetFocusedRowCellValue("DosyaNo").ToStr();

                        //Image img = CropFromCenter(Image.FromFile(@"I:\MyDISK\D\Users\Universal\Desktop\Yeni klasör\Article_39132.jpg"), 380);
                        KalikoImage sharpimg = new KalikoImage(i2).GetThumbnailImage(i2.Width / 2, i2.Height / 2, ThumbnailMethod.Fit);
                        //sharpimg.SaveJpg("test2.jpg", 90);

                        MyData.xKaliteKontrolRow r = ds.xKaliteKontrol.NewxKaliteKontrolRow();
                        r.DosyaNo = DosyaNo;
                        //r.Dosya = ConvertImageToByteArray(sharpimg.Unsharpen());

                        sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2F, 0.5F, 20));   //threshold: http://www.damiensymonds.com.au/tut_usm.html
                        using (MemoryStream mstr = new MemoryStream())
                        {
                            sharpimg.SaveJpg(mstr, 90);
                            sharpimg.Dispose();
                            r.Dosya = mstr.ToArray();
                        }

                        ds.xKaliteKontrol.AddxKaliteKontrolRow(r);

                        ExecuteNonQuery("InsKaliteKontrol", ds.xKaliteKontrol);

                        int Adet = 0;
                        int.TryParse(gridView1.GetFocusedRowCellValue("Sayfa").ToString(), out Adet);
                        gridView1.SetFocusedRowCellValue("Sayfa", Adet + 1);
                        ds.xKaliteKontrol.Clear();
                        GC.Collect();
                    }
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
                bbiResimCek.Enabled = bbiLanscape.Enabled = true;
            }

        }

        public Image CropFromCenter(Image bmp, int size)
        {
            Rectangle cropRect = new Rectangle((bmp.Width / 2) - (size / 2), (bmp.Height / 2) - (size / 2), size, size);

            Bitmap target = new Bitmap(size, size);

            using (Graphics g = Graphics.FromImage(target))
            {
                g.DrawImage(bmp, new Rectangle(0, 0, target.Width, target.Height),
                                 cropRect,
                                 GraphicsUnit.Pixel);
            }

            return target;
        }


        //void ExecQueryTV(string SP, params object[] p)
        //{
        //    using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
        //    {
        //        sqlConn.Open();
        //        SqlCommand sqlCmd = sqlConn.CreateCommand();
        //        sqlCmd.CommandText = SP;
        //        sqlCmd.CommandType = CommandType.StoredProcedure;
        //        SqlParameter[] parameters = new SqlParameter[1];
        //        parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
        //        parameters[0].Value = p[0];
        //        sqlCmd.Parameters.Add(parameters[0]);
        //        sqlCmd.ExecuteNonQuery();
        //    }
        //}



    }
}
